﻿// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;
using GisSharpBlog.NetTopologySuite.Geometries;
using GeoAPI.Geometries;

public partial class TableValuedFunctions
{
	/// <summary>
	/// 
	/// </summary>
	/// <param name="table_name"></param>
	/// <param name="column_name"></param>
	/// <param name="ewkb"></param>
	/// <returns>TABLE(oid bigint)</returns>
	/// <example>
	/// Usage:
	///		SELECT t.* 
	///		FROM ST.FilterQuery('GEOTABLE', 'GEOCOLUMN', ST.MakeEnvelope(1000,1000,2000,2000,-1)) AS q
	///		INNER JOIN GEOTABLE AS t ON q.oid = t.oid
	/// 
	/// Or the equivalent:
	///		SELECT * 
	///		FROM ST.FilterQuery#dbo#GEOTABLE#GEOCOLUMN(ST.MakeEnvelope(1000,1000,2000,2000,-1))
	/// 
	/// </example>
	[SpatialQuery]
	[SqlFunction(
		 FillRowMethodName = SpatialQuery.FillRow
		, TableDefinition = SpatialQuery.TableDefinition
	    , DataAccess = DataAccessKind.Read
		, SystemDataAccess = SystemDataAccessKind.Read
	)]
	public static IEnumerable FilterQuery(
		SqlString table_name,
		SqlString column_name,
		SqlBytes ewkb)
	{
		return SpatialQuery.Execute(table_name, column_name, ewkb, SqlString.Null, FilterQueryHandler);
	}

	[SpatialQuery]
	[SqlFunction(
		 FillRowMethodName = SpatialQuery.FillRow
		, TableDefinition = SpatialQuery.TableDefinition
		, DataAccess = DataAccessKind.Read
		, SystemDataAccess = SystemDataAccessKind.Read
	)]
	public static IEnumerable FilterQueryWhere(
		SqlString table_name,
		SqlString column_name,
		SqlBytes ewkb,
		SqlString condition)
	{
		return SpatialQuery.Execute(table_name, column_name, ewkb, condition, FilterQueryHandler);
	}

	private static IEnumerable FilterQueryHandler(SqlDataReader reader, IGeometry geometry, SpatialQuery.Arguments args)
	{
		List<Int64> oids = new List<Int64>();
		while (reader.Read())
		{
			oids.Add((long)reader.GetValue(0));
		}
		return oids;
	}


};

